package com.ruoyi.project.easyexcel;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;
import java.util.Map;

/**
 * @Author huyunqiang
 * @Description 这个是比较简单逻辑，map和cols都要在使用策略时手动拼装进来，
 * 逻辑就是遍历每一行，如果是要合并的起始列，遍历cols要合并的列，合并行。
 * @Date 2022/11/11 11:13
 **/
@Data
@AllArgsConstructor
public class MyMergeStrategy implements RowWriteHandler {

    //合并的起始行：key：开始，value；结束
    private Map<Integer, Integer> map;

    //要合并的列
    private List<Integer> cols;

//    @Override
    public void afterRowDispose(RowWriteHandlerContext context) {
        //如果是head或者当前行不是合并的起始行，跳过
        if (context.getHead() || !map.containsKey(context.getRowIndex())) {
            return;
        }
        Integer endrow = map.get(context.getRowIndex());
        //编列合并的列，合并行
        System.out.println("endrow=========="+endrow);
        System.out.println("context.getRowIndex()=========="+context.getRowIndex());
        for (Integer col : cols) {
            // CellRangeAddress(起始行,结束行,起始列,结束列)
            context.getWriteSheetHolder().getSheet().addMergedRegionUnsafe(new CellRangeAddress(context.getRowIndex(), endrow, col, col));
        }
    }

    @Override
    public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer integer, Integer integer1, Boolean aBoolean) {

    }

    @Override
    public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer integer, Boolean aBoolean) {


    }

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer integer, Boolean aBoolean) {

    }
}
